package com.design.graduation.asdemo.network;

import com.design.graduation.asdemo.Constant;
import com.design.graduation.asdemo.utils.PreferenceUtils;
import com.design.graduation.asdemo.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;

/**
 * @author by weijianxing on 10/13/15.
 */
public final class HttpServiceFactory {

    private static String url = "http://zfxtsdie.applinzi.com/php/";

    private static Retrofit retrofit;

    private HttpServiceFactory() {

    }

    private static Map<String, Object> httpServiceMap = new HashMap<>();

    public static Retrofit getRetrofit() {

        if (retrofit == null) {
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory
                    (GsonConverterFactory.create(gson)).addCallAdapterFactory
                    (RxJavaCallAdapterFactory.create()).build();
        }

        if (!StringUtils.isEmpty(getToken())) {
            retrofit.client().interceptors().add(new Interceptor() {

                @Override
                public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                    Request request = chain.request().newBuilder().header("Authorization",
                            "Bearer " + getToken()).build();
                    return chain.proceed(request);
                }

            });
        }
        return retrofit;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getService(Class<T> serviceClass) {
        String serviceName = serviceClass.getName();
        Object service = httpServiceMap.get(serviceName);
        if (service == null) {
            service = getRetrofit().create(serviceClass);
            httpServiceMap.put(serviceName, service);
        }

        return (T) service;
    }

    private static String getToken() {
        return PreferenceUtils.getString(Constant.kToken);
    }
}
